import { defineStore } from 'pinia'
import { ref } from 'vue'
import request from '@/utils/request'

export const useOrderStore = defineStore('order', () => {
  // 状态
  const orders = ref<any[]>([])
  const loading = ref(false)
  const total = ref(0)

  // 获取订单总数
  const getOrderCount = async () => {
    try {
      const response = await request.get('/orders/list', {
        params: {
          pageNum: 1,
          pageSize: 1
        }
      })
      console.log('订单总数API响应:', response)
      
      if (response && response.data && response.data.allRow !== undefined) {
        return response.data.allRow
      } else {
        return 0
      }
    } catch (error) {
      console.error('获取订单总数失败:', error)
      return 0
    }
  }

  // 获取总交易额（只计算已完成订单的金额之和）
  const getTotalRevenue = async () => {
    try {
      // 获取所有订单数据来计算总交易额
      const response = await request.get('/orders/list', {
        params: {
          pageNum: 1,
          pageSize: 1000 // 获取足够多的订单
        }
      })
      console.log(response.data.data);
      if (response && response.data && response.data.data) {
        const orders = response.data.data
        
        
        // 只计算已完成订单的金额之和
        const totalRevenue = orders.reduce((sum: number, order: any) => {
          // 根据后端数据结构，tradeStatus为true表示交易已完成
          if (order.tradeStatus === true) {
            return sum + (order.buyPrice || 0)
          }
          return sum
        }, 0)
        
        return totalRevenue
      } else {
        return 0
      }
    } catch (error) {
      console.error('获取总交易额失败:', error)
      return 0
    }
  }

  return {
    orders,
    loading,
    total,
    getOrderCount,
    getTotalRevenue
  }
}) 